include(RunCMake)

function(install_test test)
  cmake_parse_arguments(ARGS "PARALLEL;NINJA;TOUCH_CACHE" "ARGS;COMPONENT" "" ${ARGN})
  set(RunCMake_TEST_BINARY_DIR ${RunCMake_BINARY_DIR}/${test}-install)
  set(RunCMake_TEST_OPTIONS -DINSTALL_PARALLEL=${ARGS_PARALLEL} -DCMAKE_INSTALL_PREFIX=install)
  set(RunCMake_TEST_OUTPUT_MERGE 1)
  if (NOT RunCMake_GENERATOR_IS_MULTI_CONFIG)
    list(APPEND RunCMake_TEST_OPTIONS -DCMAKE_BUILD_TYPE=Debug)
  endif()
  if (ARGS_COMPONENT)
    list(APPEND ARGS_ARGS "--component ${ARGS_COMPONENT}")
  endif()
  run_cmake(install)
  set(RunCMake_TEST_NO_CLEAN 1)
  if (ARGS_TOUCH_CACHE)
    run_cmake_command(${test}-sleep ${CMAKE_COMMAND} -E sleep 2)
    run_cmake_command(${test}-touch
      ${CMAKE_COMMAND} -E touch ${RunCMake_TEST_BINARY_DIR}/CMakeFiles/cmake.check_cache)
  endif()
  if (ARGS_NINJA)
    if (ARGS_PARALLEL)
      set(INSTALL_COUNT 5)
    else()
      set(INSTALL_COUNT 1)
    endif()
    set(RunCMake-check-file check-num-installs.cmake)
    run_cmake_command(${test}-install ${CMAKE_COMMAND} --build . --config Debug ${ARGS_ARGS})
    unset(RunCMake-check-file)
  else()
    if (ARGS_COMPONENT)
      if(ARGS_COMPONENT MATCHES "^[a-zA-Z0-9_.+-]+$")
        set(INSTALL_MANIFEST "install_manifest_${ARGS_COMPONENT}.txt")
      else()
        string(MD5 COMPONENT_HASH "${ARGS_COMPONENT}")
        set(INSTALL_MANIFEST "install_manifest_${COMPONENT_HASH}.txt")
      endif()
      set(INSTALL_COUNT 0)
    else()
      set(INSTALL_MANIFEST "install_manifest.txt")
      set(INSTALL_COUNT 5)
    endif()
    set(INSTALL_MANIFEST ${RunCMake_TEST_BINARY_DIR}/${INSTALL_MANIFEST})
    set(RunCMake-check-file check-manifest.cmake)
    run_cmake_command(${test}-install ${CMAKE_COMMAND} --install . ${ARGS_ARGS})
    unset(RunCMake-check-file)
  endif()
endfunction()

install_test(parallel PARALLEL ARGS "-j 4")
install_test(no-parallel ARGS "-j 4")
install_test(out-of-date-json TOUCH_CACHE PARALLEL ARGS "-j 4")
install_test(component PARALLEL ARGS "-j 4" COMPONENT "ALPHANUMERIC123")
install_test(component-hash PARALLEL ARGS "-j 4" COMPONENT "@#$")

if(RunCMake_GENERATOR MATCHES "Ninja")
  install_test(ninja-parallel ARGS "-t install/parallel" NINJA PARALLEL)
  install_test(ninja-no-parallel ARGS "-t install" NINJA)
endif()
